import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getUserTempId } from '@/utils/getUserTempId'
import store from '@/store'

const ajax = axios.create({
  baseURL: '/api',
  timeout: 1000,
})

ajax.interceptors.request.use((config) => {
  NProgress.start()
  const token = store.state.user.user.token
  if (token) {
    config.headers.token = token
  }
  config.headers.userTempId = getUserTempId()
  return config
})

ajax.interceptors.response.use(
  (response) => {
    NProgress.done()
    return response.data
  },
  (error) => {
    console.log('响应失败')
    NProgress.done()
    return Promise.reject(new Error(error.message))
  }
)

export default ajax
